package com.netintech.core.security.service;

import javax.annotation.Resource;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.netintech.common.constant.Constants;
import com.netintech.common.exception.CustomException;
import com.netintech.common.exception.user.CaptchaException;
import com.netintech.common.exception.user.CaptchaExpireException;
import com.netintech.common.exception.user.UserPasswordNotMatchException;
import com.netintech.common.utils.MessageUtils;
import com.netintech.core.manager.AsyncManager;
import com.netintech.core.manager.factory.AsyncFactory;
import com.netintech.core.redis.RedisCache;
import com.netintech.core.security.LoginUser;

/**
 * 登录校验方法
 *
 * @author admin
 */
@Component
public class SysLoginService {

    @Value("${rsa.private_key}")
    private String privateKey;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     *每次登录都会生成新的uuid，加密后作为token，将用户信息存到数据库中
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public LoginUser  login(String username, String password, String code, String uuid) {
        /** 去掉验证码和rsa解密
//        从redis中根据验证码的key获取验证码
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
//        立即删除redis中的验证码
        redisCache.deleteObject(verifyKey);
//        判断redis中验证码
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
//        判断传过来的验证码是否相同
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }

        // 密码解密
        RSA rsa = new RSA(privateKey, null);
        password = new String(rsa.decrypt(password, KeyType.PrivateKey));
         */
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
//        登录成功
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//        用户对象
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token

        loginUser.setToken(tokenService.createToken(loginUser));
        return loginUser;
    }
}
